package com.xsq.rpc.provider.rpc;

import com.xsq.rpc.common.util.RpcRequestDecoder;
import com.xsq.rpc.provider.service.UserServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;


/**
 * @ClassName RpcServer
 * @Description TODO
 * @Author xsq
 * @Date 2020/5/30 16:41
 **/

public class RpcServer {

    public static void startServer(String hostName, int port) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //对RpcRequest实体解码获取客户端发送的内容,用StringEncoder编码把字符串发送给客户端
                        pipeline.addLast(new RpcRequestDecoder())
                                .addLast(new StringEncoder())
                                .addLast(new UserServerHandler());

                    }
                });
        try {
            serverBootstrap.bind(hostName, port).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

